//
//  YZMBankCardService.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/22.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMBankCardService.h"
#import "YZMProvince.h"
#import "YZMCity.h"
#import "YZClient.h"
#import "YZMUserService.h"
#import "YZMBankModel.h"
#import <NSArray+LinqExtensions.h>

@interface YZMBankCardService()

@property (nonatomic, strong) NSArray *provinceList;
@property (nonatomic, strong) NSDictionary *cityDictionary;
@property (nonatomic, assign) BOOL fetchedFlag;

@end

@implementation YZMBankCardService

+ (instancetype)sharedService
{
    static YZMBankCardService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    
    return sInstance;
}

- (instancetype)init{
    
    self = [super init];
    if (self) {
        _bankList = [self createDecoder];
    }
    return self;
}

- (void)initBankInfo{
    
    if (!self.fetchedFlag) {
     
        [self fetchBankListSuccess:nil failure:nil];
    }
}

#pragma mark -- Public Method

- (void)fetchBankListSuccess: (void (^)())sucess failure: (void (^)(NSError *error))failure{
    
    [YZClient bc_fetchBankListWithSuccess:^(NSURLResponse *response, id responseObject){
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            _bankList = topModel.data;
            if (_bankList && _bankList.count != 0) {
                
                [self createEncoder:_bankList];
                self.fetchedFlag = YES;
            }
            
            if (sucess) {
                
                sucess();
            }
            
        }else{
            
            if (failure) {
                
                failure([NSError yz_errorWithBadResponse]);
            }
        }
        
    } failure:^(NSError *error){
        
        if (failure) {
            
            failure(error);
        }
    }];
}

- (NSArray *)fetchCityListForProvince:(YZMProvince *)province{
    
    return self.cityDictionary[province.indexKey] ;
}

- (NSString *)formatBankCardWithHide:(NSString *)bankCard{
    
    return [bankCard stringByReplacingCharactersInRange:NSMakeRange(4, bankCard.length - 8) withString:@" *** *** "];
}


#pragma mark -- Getter

- (NSArray *)provinceList{
    
    if (!_provinceList) {
        
        NSFileManager *manage = [NSFileManager defaultManager];
        
        NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ProvinceList"];
        
        if ([manage fileExistsAtPath:path]) {
            
            NSError *error = nil;
            id array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:&error];
            
            _provinceList = [array linq_select:^id(NSArray *data){
                
                return [YZMProvince mapResponseArray:data];
            }];
        }
    }
    
    return _provinceList;
}

- (NSDictionary *)cityDictionary{
    
    if (!_cityDictionary) {
        
        NSFileManager *manage = [NSFileManager defaultManager];
        
        NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CityList"];
        
        if ([manage fileExistsAtPath:path]) {
            
            NSError *error = nil;
            id array = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:&error];
            
            NSArray *_cityList = [array linq_select:^id(NSArray *data){
                
                return [YZMCity mapResponseArray:data];
            }];
            
            _cityDictionary = [_cityList linq_groupBy:^id(YZMCity *city){
                
                return city.indexKey;
            }];
            
        }
    }
    
    return _cityDictionary;
}


#define sYZMBankListDefault   @"YZMBankListDefault"

- (void)createEncoder:(NSArray *)bankList{
    
    NSMutableData *data = [NSMutableData data];
    //创建一个归档类
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:bankList forKey:sYZMBankListDefault];
    [archiver finishEncoding];
    //将数据写入文件里
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:sYZMBankListDefault];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSArray *)createDecoder{
    
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:sYZMBankListDefault];
    
    if (data && data.length != 0) {
        
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        
        NSArray *array = [unarchiver decodeObjectForKey:sYZMBankListDefault];
        [unarchiver finishDecoding];
        
        return array;
    }
    
    return nil;
}

@end
